<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/22
 * Time: 14:10
 */
/*
 * $lat 纬度，$lng 经度
 */
use App\Services\OSS;




if (!function_exists('curl_get')) {
    function curl_get($url, $data)
    {
        $api = $url;

        //参数
        $arr_params = $data;

        $http_query = http_build_query($arr_params);

        $api = $api . "?" . $http_query;

        // 初始化 curl 会话
        $ch = curl_init($api);

        // 设置请求发送方式：get
        curl_setopt($ch, CURLOPT_HTTPGET, true);

        // 设置超时时间为：30
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);

        // 设置返回值，是否接受返回值
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);


        // 执行发起请求，获取微信服务器的返回值，格式为 json.
        $return = curl_exec($ch);
        curl_close($ch);
        return $return;
    }
}

if (!function_exists('desc_str')) {
    function desc_str($str)
    {
        $len = strlen($str); //函数返回字符串的长度：
        $new_str = "";
        for ($i = $len - 1; $i >= 0; $i--) {
            $new_str .= $str[$i];
        }
        return $new_str;
    }
}


if (!function_exists('re')){
    /**
     * 返回响应体
     * @param $data mixed
     * @param $code int
     * @param $msg string
     *
     * @return void
     *
     * */
    function re($data = [], $code = 200, $msg = '') {
        $resp = ['data' => $data, 'code' => $code, 'msg' => $msg];
        die(resp($resp));
    }
}

if (!function_exists('resp')){
    /**
     * 返回响应体
     * @param $resp array
     *
     * @return void
     *
     * */
    function resp($resp) {
        response()->json($resp, 200)->send();
    }
}

if (!function_exists('uploadFile')){
    /**
     * 上传图片并返回路径
     * @param $file \Illuminate\Http\UploadedFile
     *
     * @return string|boolean
     *
     * */
    function uploadFile($file) {
        $picpath = $file->getRealPath();
        $fileName = uniqid(str_random(8)) . '.' . $file->getClientOriginalExtension();
        $bucket = config('alioss.BucketName');
        $object =  config('alioss.OSSDIR') ."/".$fileName;
        $res = OSS::publicUpload($bucket,$object, $picpath);
        if ($res){
         return $object;
        }else{
            return false;
        }
    }
}

//验证身份证号
if(!function_exists('is_idcard')){
    function is_idcard( $id )
    {
        $id = strtoupper($id);
        $regx = "/(^\d{15}$)|(^\d{17}([0-9]|X)$)/";
        $arr_split = array();
        if(!preg_match($regx, $id))
        {
            return FALSE;
        }
        if(15==strlen($id)) //检查15位
        {
            $regx = "/^(\d{6})+(\d{2})+(\d{2})+(\d{2})+(\d{3})$/";

            @preg_match($regx, $id, $arr_split);
            //检查生日日期是否正确
            $dtm_birth = "19".$arr_split[2] . '/' . $arr_split[3]. '/' .$arr_split[4];
            if(!strtotime($dtm_birth))
            {
                return FALSE;
            } else {
                return TRUE;
            }
        }
        else      //检查18位
        {
            $regx = "/^(\d{6})+(\d{4})+(\d{2})+(\d{2})+(\d{3})([0-9]|X)$/";
            @preg_match($regx, $id, $arr_split);
            $dtm_birth = $arr_split[2] . '/' . $arr_split[3]. '/' .$arr_split[4];
            if(!strtotime($dtm_birth)) //检查生日日期是否正确
            {
                return FALSE;
            }
            else
            {
                //检验18位身份证的校验码是否正确。
                //校验位按照ISO 7064:64:1983.MOD 11- 11-2的规定生成，X可以认为是数字10。
                $arr_int = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
                $arr_ch = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
                $sign = 0;
                for ( $i = 0; $i < 17; $i++ )
                {
                    $b = (int) $id{$i};
                    $w = $arr_int[$i];
                    $sign += $b * $w;
                }
                $n = $sign % 11;
                $val_num = $arr_ch[$n];
                if ($val_num != substr($id,17, 1))
                {
                    return FALSE;
                } // //phpfensi.com

                else
                {
                    return TRUE;
                }
            }
        }

    }
}

/*手机号码判断*/
if (!function_exists('is_mobile')) {
    function is_mobile($mobile)
    {
        $reg = "/^1[3456789]\d{9}$/";
        if (!preg_match($reg, $mobile)) {
            return false;
        }
        return true;
    }
}

/*数据库setting表操作*/
if (!function_exists('Setting')) {

    function Setting()
    {
        return app('App\Models\Seting');
    }

}

/*邮箱判断*/
if (!function_exists('is_email')) {
    function is_email($email)
    {
        $reg = "/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/";
        if (preg_match($reg, $email)) {
            return true;
        }
        return false;
    }
}

/*创建唯一订单号*/
if (!function_exists('random_number')) {
    function random_number($length = 11)
    {
        $pool = '0123456789';
        return substr(str_shuffle(str_repeat($pool, $length)), 0, $length);
    }
}
if (!function_exists('randomkeys')) {
    function randomkeys($length){
        if( empty($chars) ){
            $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        }
        $chars = str_shuffle($chars);
        $num = $length < strlen($chars) - 1 ? $length:str_len($chars) - 1;
        return substr($chars,0,$num);
    }
}

//base64圖片上传
if (!function_exists('base64img_oss')) {
     function base64img_oss($oss_config , $imgbase64 ,$folder = '',  $savename = ''  )
    {
        //保存base64图片
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $imgbase64, $result))
        {
            $type = $result[2];

            if(empty($savename))
            {
                $savename = uniqid().'.'.$type;
            }
            $path = '';
            if(!empty($folder))
            {
                $path = $oss_config['OSSDIR'] . $folder ;
            }
            else
            {
                $path = $oss_config['OSSDIR'] ;
            }

            //存储
            $file = $path.'/'.$savename;
            $save_path = str_replace('//', '/', $file);


            $savename = $_SERVER['DOCUMENT_ROOT'] .'/'.$savename;

            // var_dump( $save_path);die;

            //临时存储到本地
            if (file_put_contents($savename, base64_decode(str_replace($result[1], '', $imgbase64))))
            {
                try
                {
                    $ossClient = new OssClient($oss_config['AccessKeyId'], $oss_config['AccessKeySecret'], $oss_config['EndPoint']);
                    $ossClient->uploadFile($oss_config['BucketName'], $save_path, $savename);
                    unlink($savename);
                }
                catch(OssException $e)
                {
                    printf(__FUNCTION__ . ": FAILED\n");
                    printf($e->getMessage() . "\n");
                    unlink($savename);
                    return -3 ;
                }
                return $save_path;

            }
            else
            {
                return -1;
            }
        }
        else
        {
            return -2;
        }

        return  $save_path ;

    }
}

if (!function_exists('array_to_tree')) {
    function array_to_tree($list, $pk = 'id', $pid = 'parent_id', $child = '_child', $root = 0)
    {
        // 创建Tree
        $tree = array();
        if (is_array($list)) {
            // 创建基于主键的数组引用
            $refer = array();
            foreach ($list as $key => $data) {
                $list[$key][$child] = [];
                $refer[$data[$pk]] =& $list[$key];
            }
            foreach ($list as $key => $data) {
                // 判断是否存在parent
                $parentId = $data[$pid];
                if ($root == $parentId) {
                    $tree[] =& $list[$key];
                } else {
                    if (isset($refer[$parentId])) {
                        $parent =& $refer[$parentId];
                        $parent[$child][] =& $list[$key];
                    }
                }
            }
        }
        return $tree;
    }
}

if (!function_exists('rand_name')) {
    function rand_name()
    {
        $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $rand = $code[rand(0,25)]
            .strtoupper(dechex(date('m')))
            .date('d').substr(time(),-5)
            .substr(microtime(),2,5)
            .sprintf('%02d',rand(0,99));
        for(
            $a = md5( $rand, true ),
            $s = '0123456789ABCDEFGHIJKLMNOPQRSTUV',
            $d = '',
            $f = 0;
            $f < 8;
            $g = ord( $a[ $f ] ),
            $d .= $s[ ( $g ^ ord( $a[ $f + 8 ] ) ) - $g & 0x1F ],
            $f++
        );
        return  $d;
    }
}
